#include "idm_window.h"
#include "ui_manager.h"
#include "theme_manager.h"
#include <QApplication>
#include <QMessageBox>
#include <QHeaderView>
#include <QTableWidgetItem>
#include <QIcon>
#include <QPixmap>
#include <QVBoxLayout>
#include <QGroupBox>
#include <QLabel>
#include <QProgressBar>
#include <QCloseEvent>
#include <QDesktopServices>
#include <QUrl>
#include <QSplitter>
#include <QLineEdit>
#include <QTreeWidget>
#include <QTabWidget>
#include <QHBoxLayout>
#include <QFormLayout>
#include <QTextEdit>
#include <QSpinBox>
#include <QCheckBox>
#include <QComboBox>
#include <QDateTime>
#include <QMenu>
#include <QContextMenuEvent>
#include <QPoint>
#include <QFrame>
#include <QStyle>
#ifdef HAVE_TEXT_TO_SPEECH
#include <QTextToSpeech>
#endif

IDMWindow::IDMWindow(QWidget *parent)
    : QMainWindow(parent)
    , m_uiManager(nullptr)
{
    // 设置窗口属性
    setWindowTitle(tr("Internet Download Manager"));
    resize(1100, 750);
    
    // 设置窗口图标（如果有的话）
    // setWindowIcon(QIcon(":/icons/idm_icon.png"));
    
    // 创建UI管理器
    m_uiManager = new UIManager(this);
    
    // 创建界面组件
    m_uiManager->createMenus();
    m_uiManager->createToolBars();
    m_uiManager->createMainWidgets();
    m_uiManager->createStatusBar();
    m_uiManager->createSystemTrayIcon();
    m_uiManager->setupConnections();
    
    // 初始化文本转语音功能
#ifdef HAVE_TEXT_TO_SPEECH
    textToSpeech = new QTextToSpeech(this);
#endif
    
    // 设置中心部件
    setCentralWidget(m_uiManager->tabWidget());
    
    // 应用当前主题样式（确保启动时正确应用浅色主题）
    m_uiManager->applyTheme();
}

IDMWindow::~IDMWindow()
{
}


// 菜单栏槽函数实现
void IDMWindow::newDownload()
{
    QMessageBox::information(this, tr("New Download"), tr("New download functionality would be implemented here."));
}

void IDMWindow::batchDownload()
{
    QMessageBox::information(this, tr("Batch Download"), tr("Batch download functionality would be implemented here."));
}

void IDMWindow::pauseDownload()
{
    QMessageBox::information(this, tr("Pause Download"), tr("Pause download functionality would be implemented here."));
}

void IDMWindow::resumeDownload()
{
    QMessageBox::information(this, tr("Resume Download"), tr("Resume download functionality would be implemented here."));
}

void IDMWindow::cancelDownload()
{
    QMessageBox::information(this, tr("Cancel Download"), tr("Cancel download functionality would be implemented here."));
}

void IDMWindow::deleteDownload()
{
    QMessageBox::information(this, tr("Delete Download"), tr("Delete download functionality would be implemented here."));
}

void IDMWindow::properties()
{
    QMessageBox::information(this, tr("Properties"), tr("Properties functionality would be implemented here."));
}

void IDMWindow::options()
{
    QMessageBox::information(this, tr("Options"), tr("Options functionality would be implemented here."));
}

void IDMWindow::exitApplication()
{
    QApplication::exit();
}

void IDMWindow::helpContents()
{
    QMessageBox::information(this, tr("Help Contents"), tr("Help contents would be displayed here."));
}

void IDMWindow::about()
{
    QMessageBox::about(this, tr("About IDM"), 
                       tr("Internet Download Manager\n"
                          "A powerful download management tool."));
}

// 工具栏槽函数实现
void IDMWindow::addUrl()
{
    QMessageBox::information(this, tr("Add URL"), tr("Add URL functionality would be implemented here."));
}

void IDMWindow::pauseSelected()
{
    QMessageBox::information(this, tr("Pause Selected"), tr("Pause selected download functionality would be implemented here."));
}

void IDMWindow::resumeSelected()
{
    QMessageBox::information(this, tr("Resume Selected"), tr("Resume selected download functionality would be implemented here."));
}

void IDMWindow::deleteSelected()
{
    QMessageBox::information(this, tr("Delete Selected"), tr("Delete selected download functionality would be implemented here."));
}

void IDMWindow::scheduleDownload()
{
    QMessageBox::information(this, tr("Schedule Download"), tr("Schedule download functionality would be implemented here."));
}

void IDMWindow::openFile()
{
    QMessageBox::information(this, tr("Open File"), tr("Open file functionality would be implemented here."));
}

void IDMWindow::openFolder()
{
    QMessageBox::information(this, tr("Open Folder"), tr("Open folder functionality would be implemented here."));
}

void IDMWindow::showProperties()
{
    QMessageBox::information(this, tr("Show Properties"), tr("Show properties functionality would be implemented here."));
}

void IDMWindow::organizeDownloads()
{
    QMessageBox::information(this, tr("Organize Downloads"), tr("Organize downloads functionality would be implemented here."));
}

void IDMWindow::deleteCompleted()
{
    QMessageBox::information(this, tr("Delete Completed"), tr("Delete completed downloads functionality would be implemented here."));
}

void IDMWindow::connectToProxy()
{
    QMessageBox::information(this, tr("Connect to Proxy"), tr("Connect to proxy functionality would be implemented here."));
}

void IDMWindow::disconnectFromProxy()
{
    QMessageBox::information(this, tr("Disconnect from Proxy"), tr("Disconnect from proxy functionality would be implemented here."));
}

void IDMWindow::refreshList()
{
    QMessageBox::information(this, tr("Refresh"), tr("Refresh download list functionality would be implemented here."));
}

void IDMWindow::showDownloadsPanel(bool show)
{
    // 控制下载面板的显示/隐藏
    // 这里可以实现面板的展开/折叠功能
}

void IDMWindow::readAloud()
{
#ifdef HAVE_TEXT_TO_SPEECH
    // 音频朗读功能实现
    QString text = tr("Internet Download Manager is running. You have 2 downloads in progress.");
    textToSpeech->say(text);
    
    QMessageBox::information(this, tr("Read Aloud"), 
                            tr("Text-to-speech functionality is now reading: \"%1\"").arg(text));
#else
    QMessageBox::information(this, tr("Read Aloud"), 
                            tr("Text-to-speech functionality is not available in this build."));
#endif
}

// 系统托盘槽函数实现
void IDMWindow::trayIconActivated(QSystemTrayIcon::ActivationReason reason)
{
    switch (reason) {
    case QSystemTrayIcon::Trigger:
        show();
        break;
    default:
        break;
    }
}

// 其他槽函数实现
void IDMWindow::showContextMenu(const QPoint &pos)
{
    QMenu contextMenu(tr("Context menu"), this);
    
    QAction *pauseAct = contextMenu.addAction(tr("Pause"));
    QAction *resumeAct = contextMenu.addAction(tr("Resume"));
    QAction *deleteAct = contextMenu.addAction(tr("Delete"));
    contextMenu.addSeparator();
    QAction *propertiesAct = contextMenu.addAction(tr("Properties"));
    QAction *readAloudAct = contextMenu.addAction(tr("Read Aloud"));
    
    // 连接动作到槽函数
    connect(pauseAct, &QAction::triggered, this, &IDMWindow::pauseSelected);
    connect(resumeAct, &QAction::triggered, this, &IDMWindow::resumeSelected);
    connect(deleteAct, &QAction::triggered, this, &IDMWindow::deleteSelected);
    connect(propertiesAct, &QAction::triggered, this, &IDMWindow::showProperties);
    connect(readAloudAct, &QAction::triggered, this, &IDMWindow::readAloud);
    
    contextMenu.exec(m_uiManager->downloadList()->viewport()->mapToGlobal(pos));
}

void IDMWindow::filterDownloads(int index)
{
    QString filter = m_uiManager->filterComboBox()->itemText(index);
    
    for (int row = 0; row < m_uiManager->downloadList()->rowCount(); ++row) {
        bool show = true;
        
        if (filter == tr("Active")) {
            QTableWidgetItem *statusItem = m_uiManager->downloadList()->item(row, 6);
            show = statusItem && (statusItem->text() == tr("Downloading"));
        } else if (filter == tr("Completed")) {
            QTableWidgetItem *statusItem = m_uiManager->downloadList()->item(row, 6);
            show = statusItem && (statusItem->text() == tr("Completed"));
        } else if (filter == tr("Paused")) {
            QTableWidgetItem *statusItem = m_uiManager->downloadList()->item(row, 6);
            show = statusItem && (statusItem->text() == tr("Paused"));
        } else if (filter == tr("Error")) {
            QTableWidgetItem *statusItem = m_uiManager->downloadList()->item(row, 6);
            show = statusItem && (statusItem->text() == tr("Error"));
        }
        
        m_uiManager->downloadList()->setRowHidden(row, !show);
    }
}

void IDMWindow::toggleCategoryPanel()
{
    // 这里需要访问UI管理器中的categoryPanelVisible变量，但目前无法直接访问
    // 可以通过切换面板的可见性来实现相同的功能
    bool isVisible = m_uiManager->categoryPanel()->isVisible();
    m_uiManager->categoryPanel()->setVisible(!isVisible);
    m_uiManager->toggleCategoryPanelAction()->setChecked(!isVisible);
}

void IDMWindow::toggleTheme()
{
    ThemeManager* themeManager = ThemeManager::instance();
    if (themeManager->currentTheme() == ThemeManager::Light) {
        themeManager->setTheme(ThemeManager::Dark);
    } else {
        themeManager->setTheme(ThemeManager::Light);
    }
    m_uiManager->applyTheme();
}

void IDMWindow::resizeEvent(QResizeEvent *event)
{
    QMainWindow::resizeEvent(event);
    
    // 调整下载列表的行数以适应窗口大小
    QTableWidget* downloadList = m_uiManager->downloadList();
    if (downloadList) {
        // 计算每行的高度（大致估算）
        int rowHeight = 20; // 假设每行高度为20像素
        int headerHeight = downloadList->horizontalHeader()->height();
        int availableHeight = downloadList->viewport()->height() - headerHeight;
        
        // 计算需要的行数
        int neededRows = availableHeight / rowHeight;
        
        // 确保至少有几行，最多不超过一个合理的上限
        neededRows = qBound(10, neededRows, 100);
        
        // 调整行数
        int currentRowCount = downloadList->rowCount();
        if (neededRows > currentRowCount) {
            // 增加行数
            for (int i = currentRowCount; i < neededRows; ++i) {
                downloadList->insertRow(i);
                // 为新行的每个单元格添加空的 QTableWidgetItem
                for (int col = 0; col < downloadList->columnCount(); ++col) {
                    QTableWidgetItem *item = new QTableWidgetItem("");
                    item->setFlags(item->flags() & ~Qt::ItemIsEditable); // 设置为不可编辑
                    downloadList->setItem(i, col, item);
                }
            }
        } else if (neededRows < currentRowCount) {
            // 减少行数
            for (int i = currentRowCount - 1; i >= neededRows; --i) {
                downloadList->removeRow(i);
            }
        }
    }
}
